import { createEffect, createEvent, createStore, sample } from 'effector';
import { condition, interval } from 'patronum';
import { sendCircularGetDataCh2, sendCircularGetDataCh3 } from 'socketApi';
import { resetStore } from 'store';

// Events
export const setCircularIntervalCh2 = createEvent<number>();
export const setCircularIntervalCh3 = createEvent<number>();

const startCircular2 = createEvent();
const stopCircular2 = createEvent();

const startCircular3 = createEvent();
const stopCircular3 = createEvent();

// Effects
const sendCircular2 = createEffect(sendCircularGetDataCh2);
const sendCircular3 = createEffect(sendCircularGetDataCh3);

// Stores
const $circularInterval2 = createStore(0)
  .on(setCircularIntervalCh2, (_, value) => value)
  .reset(resetStore);

const $circularInterval3 = createStore(0)
  .on(setCircularIntervalCh3, (_, value) => value)
  .reset(resetStore);

// Controlled Timers (Patronum)
const { tick: tick2 } = interval({
  timeout: $circularInterval2,
  start: startCircular2,
  stop: stopCircular2,
});

const { tick: tick3 } = interval({
  timeout: $circularInterval3,
  start: startCircular3,
  stop: stopCircular3,
});

// Rules (Patronum)
condition({
  source: $circularInterval2,
  if: 0,
  then: stopCircular2,
  else: startCircular2,
});

condition({
  source: $circularInterval3,
  if: 0,
  then: stopCircular3,
  else: startCircular3,
});

sample({
  clock: tick2,
  target: sendCircular2,
})

sample({
  clock: tick3,
  target: sendCircular3,
})
